package com.putong35.common.httprequest.app;

import android.text.TextUtils;
import android.util.Log;

import java.util.Calendar;

/**
 * Simple to Introduction
 *
 * @Author: PengWeiwei
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017-04-06
 * @Version: 1.0.0
 */

public class Token {

    private static TokenInfo mTokenInfo; // token info 是个单例， 且不能为空
    private static Token mToken;


    public TokenInfo getTokenInfo() {
        if (mTokenInfo == null) {
            mTokenInfo = TokenInfo.createFromSp();
        }
        return mTokenInfo;
    }

    public static Token getInstance() {
        if (mToken == null) {
            mToken = new Token();
        }
        return mToken;
    }

    /**
     * 判断token是否有效
     *
     * @return
     */
    public boolean isTokenValid() {
        boolean ret;
        TokenInfo tokenInfo = getTokenInfo();
        if (tokenInfo == null) {
            ret = false;
        } else {
            if (TextUtils.isEmpty(tokenInfo.getAccessToken())) {
                Log.e("zf", "AccessToken is Empty");
                ret = false;
            } else if (isExpire(tokenInfo)) {  //expires_at='2016-08-01T16:21:58.218+0800', server_time='2016-07-18T16:21:58.218+0800'
                ret = false;
            } else {
                ret = true;
            }
        }

        return ret;
    }

    public static boolean isExpire(TokenInfo tokenInfo) {
        // TODO  SERVER TODO
        if (!TextUtils.isEmpty(tokenInfo.getAccessToken())) {
            return false;
        }
        if (tokenInfo.getExpiresAt() == null) {
            return false;
        }
        long expiresAt = Long.parseLong(tokenInfo.getExpiresAt());
        long currTime = Calendar.getInstance().getTimeInMillis();
//            Log.e("zf_time", "expiresAt :" + expiresAt + '\n' + "currTime :" + currTime);
        if (expiresAt - currTime <= 0) { //604800000为7天的毫秒数
            return true;
        }
        return false;
    }

    /**
     * 更新token的信息
     *
     * 用户登录之后会获取到token信息，用户需要调用此方法保存
     *
     * @param tokenInfo
     * @return
     */
    public TokenInfo updateTokenInfo(TokenInfo  tokenInfo) {
        if (tokenInfo != null) {
            mTokenInfo = getTokenInfo();
            mTokenInfo.setAccessToken(tokenInfo.getAccessToken());
            mTokenInfo.setServerTime(tokenInfo.getServerTime());
            mTokenInfo.setRefreshToken(tokenInfo.getRefreshToken());
            mTokenInfo.setExpiresAt(tokenInfo.getExpiresAt());
            mTokenInfo.setMacKey(tokenInfo.getMacKey());
        }
        return mTokenInfo;
    }


    public void clear() {
        getTokenInfo().clear();
    }


}
